package com.seckill.goods.task.dynamic;

import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @program: seckill-parent
 * @description: 任务的命名空间
 * @author: zhanghz001
 * @create: 2021-06-27 11:39
 **/

// @Component
public class ZhzElasticJobHandler {
    @Autowired
    private ZookeeperRegistryCenter zookeeperRegistryCenter;
    @Autowired
    private ZhzElasticJobListener zhzElasticJobListener;
    
    /****
     * 动态添加定时任务,也就是特定时间执行的定时任务
     */
    public void addTask(String jobName, String cron, Integer count, SimpleJob instance, String actid) {
        LiteJobConfiguration.Builder builder = LiteJobConfiguration.newBuilder(
                //定时任务配置信息,
                // 定时任务的字节码信息
                new SimpleJobConfiguration(
                        JobCoreConfiguration.
                                //命名空间名字,执行周期表达式,分片个数
                                        newBuilder(
                                        jobName,
                                        cron,
                                        count
                                )
                                //额外配置,自定义参数
                                .jobParameter(actid)
                                .build(),
                        //定时任务的字节码信息
                        instance.getClass().getName()
                )
        );
        
        //本地配置覆盖注册中心配置,生成配置对象
        LiteJobConfiguration jobConfig = builder.overwrite(true).build();
        
        //创建实际执行的定时任务
        new SpringJobScheduler(instance, zookeeperRegistryCenter, jobConfig, zhzElasticJobListener);
    }
    
    /**
     * date转cron表达式
     */
    public static final String CRON_ON_FORMAT = "ss mm HH dd MM ? yyyy";
    
    /**
     * 获得定时
     */
    public static String getCron(final Date date) {
        SimpleDateFormat format = new SimpleDateFormat(CRON_ON_FORMAT);
        return format.format(date);
    }
    
    public static void main(String[] args) {
        System.out.println(getCron(new Date()));
    }
    
}
